package org.argus.job.server.system.management.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.argus.common.core.domain.R;
import org.argus.job.common.request.TaskTrackerReportInstanceStatusReq;
import org.argus.job.common.request.WorkerHeartbeat;
import org.argus.job.common.request.WorkerLogReportReq;
import org.argus.job.server.remote.worker.WorkerClusterManagerService;
import org.argus.job.server.system.domain.AppInfo;
import org.argus.job.server.system.instance.InstanceLogService;
import org.argus.job.server.system.instance.InstanceManager;
import org.argus.job.server.system.management.service.AppInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.ExecutionException;

import static org.argus.job.common.RemoteConstant.S4W_HANDLER_REPORT_INSTANCE_STATUS;
import static org.argus.job.common.RemoteConstant.S4W_HANDLER_REPORT_LOG;

/**
 * worker节点请求处理
 * @Author 刘文/Cliff Liu
 * @Date 2024/11/9
 */
@RestController
@RequestMapping("/server")
@Api("worker节点请求处理")
@Slf4j
public class ServerController {

    @Autowired
    private AppInfoService service;

    @Autowired
    private InstanceManager instanceManager;

    @Autowired
    private InstanceLogService instanceLogService;

    @PostMapping("/workerHeartbeat")
    @ApiOperation("Worker 节点心跳")
    public R<Void> workerHeartbeat(@RequestBody WorkerHeartbeat heartbeat) {
        WorkerClusterManagerService.updateStatus(heartbeat);
        return R.ok();
    }

    @PostMapping(S4W_HANDLER_REPORT_INSTANCE_STATUS)
    @ApiOperation("处理 TaskTracker 上报的任务实例状态")
    public R<Void> reportInstanceStatus(@RequestBody TaskTrackerReportInstanceStatusReq req) {
        try{
            instanceManager.updateStatus(req);
        } catch (ExecutionException e) {
            log.error("处理 TaskTracker 上报的任务实例状态失败", e);
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    @PostMapping(S4W_HANDLER_REPORT_LOG)
    @ApiOperation("提交日志记录，持久化到本地数据库中")
    public R<Void> submitLogs(@RequestBody WorkerLogReportReq req) {
        instanceLogService.submitLogs(req.getWorkerAddress(), req.getInstanceLogContents());
        return R.ok();
    }

    @GetMapping("/assert")
    public R<Long> assertAppName(String appName) {
        AppInfo appInfo = service.findByAppName(appName);
        if (appInfo != null) {
            return R.ok(appInfo.getId());
        }
        return R.fail(String.format("app(%s) is not registered! Please register the app in oms-console first.", appName));
    }
}
